package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 自动实例化与当前ReflectDemo8在同一个包下所有被@AutoRunClass标注的类
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception{
        File file =new File(ReflectDemo8.class.getResource(".").toURI());
        File []dirs =file.listFiles(f->f.getName().endsWith(".class"));
        for (File dir:dirs){
            String filename = dir.getName().substring(0,dir.getName().indexOf("."));
            Class cls =Class.forName(ReflectDemo8.class.getPackage().getName()+"."+filename);
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                System.out.println(filename+"被实例化");
                Object o =cls.newInstance();
                System.out.println(o);
                Method []methods =cls.getDeclaredMethods();
                for(Method method :methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int num =arm.value();
                        System.out.println("自动调用方法:"+method.getName()+":"+num+"次");
                        for (int i = 0; i <num ; i++) {
                            method.invoke(o);
                        }
                    }
                }
            }
        }
    }
}
